<template>
	<view class="page">
		<view class="header">
			<view class="left">
				<view class="menu-icon" @click="onMenu"><uni-icons type="list" size="20" color="#000"></uni-icons></view>
			</view>
			<view class="tools">
				<uni-icons type="search" size="24" color="#000" @click="onSearch"></uni-icons>
				<view class="plus-wrap">
					<uni-icons type="plus" size="26" color="#000" @click="toggleMenu"></uni-icons>
					<view v-if="menuOpen" class="plus-menu" @click.stop>
						<view class="menu-item" @click="openAddFriend"><uni-icons type="contact" size="20"></uni-icons><text>添加朋友</text></view>
						<view class="menu-item" @click="toast('发起群聊')"><uni-icons type="chatboxes" size="20"></uni-icons><text>发起群聊</text></view>
						<view class="menu-item" @click="toast('扫一扫')"><uni-icons type="search" size="20"></uni-icons><text>扫一扫</text></view>
						<view class="menu-item" @click="toast('建立火花关系')"><uni-icons type="star-filled" size="20"></uni-icons><text>建立火花关系</text></view>
					</view>
				</view>
			</view>
		</view>

		<!-- 复用首页的侧边抽屉 -->
		<SideDrawer ref="sideDrawerRef" :user="user" @login="handleLogin" @logout="handleLogout" />

		<!-- 顶部好友头像横滑 -->
		<scroll-view scroll-x class="top-avatars" :show-scrollbar="false" v-if="friendsList && friendsList.length">
			<view class="avatar-item" v-for="f in friendsList" :key="'top-'+f.id" @click="openChat(f)">
				<image class="avatar" :src="f.avatar" mode="aspectFill"></image>
				<text class="avatar-name">{{ f.name }}</text>
			</view>
		</scroll-view>

		<scroll-view scroll-y class="list">
			<uni-swipe-action>
				<uni-swipe-action-item
					v-for="f in friendsList"
					:key="f.id"
					:right-options="swipeOptions"
					@click="(e)=>onSwipeClick(e,f.id)"
				>
					<view class="item" @click="openChat(f)">
						<image class="avatar" :src="f.avatar" mode="aspectFill"></image>
						<view class="meta">
							<view class="row">
								<text class="name">{{ f.name }}</text>
								<text class="time" v-if="lastTime(f.id)">{{ lastTime(f.id) }}</text>
							</view>
							<view class="row">
								<text class="preview">{{ lastPreview(f.id) || '打个招呼吧～' }}</text>
								<view class="badge" v-if="unread(f.id) > 0">{{ unread(f.id) > 99 ? '99+' : unread(f.id) }}</view>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</scroll-view>

		<BottomNav :activeTab="'messages'" :unreadCount="unreadTotalNum" @navChange="goTab"/>

		<uni-popup ref="addPopup" type="dialog">
			<view class="popup">
				<text class="popup-title">添加好友</text>
				<uni-easyinput v-model="newName" placeholder="输入好友昵称"></uni-easyinput>
				<button class="btn" type="primary" @click="confirmAdd">添加</button>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import BottomNav from '@/components/BottomNav/BottomNav.vue'
import SideDrawer from '@/components/SideDrawer/SideDrawer.vue'
import { friends as friendsRef, addFriend, deleteFriend, getConversation, unreadTotal, clearUnread } from '@/utils/chatStore.js'

const friendsList = computed(() => friendsRef.value)
const unreadTotalNum = computed(() => unreadTotal())

const swipeOptions = [
	{ text: '删除', style: { backgroundColor: '#ff3b30', color: '#fff' } }
]

const addPopup = ref(null)
const newName = ref('')
const menuOpen = ref(false)

// 侧边抽屉与用户状态（与首页保持一致）
const sideDrawerRef = ref(null)
const user = ref({ isLoggedIn: false, nickname: '', avatar: '', uid: '' })
const STORAGE_USER_KEY = 'dy_user_state'

function onMenu() {
	if (sideDrawerRef.value && typeof sideDrawerRef.value.open === 'function') {
		sideDrawerRef.value.open()
	}
}

function handleLogin() { try { uni.navigateTo({ url: '/pages/login/login' }) } catch (e) { uni.redirectTo({ url: '/pages/login/login' }) } }
function handleLogout() { user.value = { isLoggedIn: false, nickname: '', avatar: '', uid: '' }; try { uni.removeStorageSync(STORAGE_USER_KEY) } catch (e) {} }

function openAddFriend() { menuOpen.value = false; try { uni.navigateTo({ url: '/pages/add-friend/add-friend' }) } catch (e) { uni.redirectTo({ url: '/pages/add-friend/add-friend' }) } }
function confirmAdd() { const name = (newName.value || '').trim(); if (!name) { uni.showToast({ title: '请输入昵称', icon: 'none' }); return } addFriend(name); addPopup.value?.close(); uni.showToast({ title: '已添加', icon: 'success' }) }
function toggleMenu() { menuOpen.value = !menuOpen.value }
function toast(t) { uni.showToast({ title: t, icon: 'none' }) }

function onSwipeClick(e, id) { if (e?.content?.text === '删除') { uni.showModal({ title: '删除好友', content: '删除后将清空与该好友的会话记录，确定继续？', success: (res) => { if (res.confirm) { deleteFriend(id); uni.showToast({ title: '已删除', icon: 'none' }) } } }) } }

function lastPreview(fid) { const conv = getConversation(fid); const last = conv.messages[conv.messages.length - 1]; return last ? last.content : '' }
function lastTime(fid) { const conv = getConversation(fid); const last = conv.messages[conv.messages.length - 1]; if (!last) return ''; const d = new Date(last.timestamp); return [d.getMonth() + 1, d.getDate()].join('/') }
function unread(fid) { return getConversation(fid).unread || 0 }
function openChat(f) { clearUnread(f.id); uni.navigateTo({ url: `/pages/chat/chat?fid=${encodeURIComponent(f.id)}&name=${encodeURIComponent(f.name)}&avatar=${encodeURIComponent(f.avatar)}` }) }
function onSearch() { uni.showToast({ title: '搜索暂未实现', icon: 'none' }) }
function goTab(tab) { if (tab === 'home') { uni.redirectTo({ url: '/pages/index/index' }) } }

onShow(() => { try { const cached = uni.getStorageSync(STORAGE_USER_KEY); if (cached && typeof cached === 'object') { user.value = cached } } catch (e) {} uni.$off('loginSuccess'); uni.$on('loginSuccess', (payload) => { if (payload && typeof payload === 'object') { user.value = payload; sideDrawerRef.value && sideDrawerRef.value.close() } }) })
</script>

<style scoped lang="scss">
.page { background: #fff; height: 100vh; padding-bottom: 120rpx; }
.header { height: 120rpx; display: flex; align-items: flex-end; justify-content: space-between; padding: 0 24rpx 16rpx; }
.header .left { display: flex; align-items: center; }
.header .menu-icon { width: 60rpx; height: 60rpx; display: flex; align-items: center; justify-content: center; }
.header .tools { display: flex; gap: 24rpx; }
.plus-wrap { position: relative; }
.plus-menu { position: absolute; top: 40rpx; right: 0; width: 360rpx; background: #fff; border-radius: 16rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.12); padding: 8rpx 0; z-index: 10; }
.menu-item { height: 88rpx; display: flex; align-items: center; gap: 16rpx; padding: 0 20rpx; font-size: 28rpx; }
.menu-item + .menu-item { border-top: 1px solid #f2f2f2; }

.top-avatars { position: relative; white-space: nowrap; padding: 12rpx 12rpx 8rpx; }
/* 美化或隐藏横向滚动条 */
.top-avatars::-webkit-scrollbar { height: 0; background: transparent; }
.top-avatars { scrollbar-width: none; }

.avatar-item { display: inline-flex; flex-direction: column; align-items: center; width: 120rpx; margin: 0 6rpx; }
.avatar-item .avatar { width: 96rpx; height: 96rpx; border-radius: 50%; box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.06); }
.avatar-name { margin-top: 6rpx; font-size: 24rpx; color: #333; max-width: 96rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center; }

.list { height: calc(100vh - 120rpx - 120rpx - 130rpx); }
.item { display: flex; align-items: center; padding: 20rpx 24rpx; border-bottom: 1px solid #f2f2f2; background: #fff; }
.avatar { width: 96rpx; height: 96rpx; border-radius: 50%; }
.meta { flex: 1; margin-left: 20rpx; }
.row { display: flex; align-items: center; justify-content: space-between; }
.name { font-size: 32rpx; font-weight: 600; }
.time { color: #9aa0a6; font-size: 24rpx; }
.preview { color: #6b7280; font-size: 26rpx; max-width: 520rpx; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.badge { min-width: 36rpx; height: 36rpx; background: #ff2442; color: #fff; border-radius: 18rpx; text-align: center; line-height: 36rpx; font-size: 22rpx; padding: 0 8rpx; }
.popup { background: #fff; padding: 24rpx; width: 600rpx; border-radius: 16rpx; }
.popup-title { font-size: 32rpx; font-weight: 600; margin-bottom: 16rpx; }
.btn { margin-top: 20rpx; }
</style>


